Dynamic arrays


Dynamic arrays is a New feature of Delphi 4. You can declare an array without size,
then you can set it's size at run time. Example:


var
A:
array of Integer;

When you need to use that array you must allocate memory space for it using
SetLength
procedure:

SetLength(A, 10);

This statement allocate 10 items for A. The range of this items will be from
0 to 9.
Dynamic arrays are always zero indexed.

Dynamic array size:


You can increase the size of array when ever needed without affecting the current
data by specifing largest number in
SetLength procedure such as:

SetLength(A, 20);

This will expand the array
10 more items and it keeps the origional data untouched.

It is very usifull to use
High function with Dynamic arrays, because it returns
the last index of the array, for example:
High(A) returns 19 if we specify 20 items in SetLength procedure.

Example:

for i:= 0 to High(A) do
Memo1.Lines.Add(A[i]);

This for loop displays all the element of array A regardless of it's current size.

High function can be used also for expanding the current array size by certain amount,
for example if you add unknown elements size to a Dynamic array (the same as linked
list) you can do this:

SetLength(A, High(A) + 2);

High will not return the actual elements number, but it returns the last index,
so that we need to add 2 because the array begins with zero.
In this case if the array contains 10 elements, High(A) will return 9, so that we
will assign 11 as a new size. If the array is not allocated yet (Empty); High(A)
will return -1. Adding 2 to High(A) also expand the array by one and the array range
will be from
0 to 0 which means only one item.

To shrink the size of Dynamic array:

SetLength(A, High(A));

If the size of
A is 20 elements, High(A) will return 19, which means that the new
size will be from
0 to 18.



Freeing Dynamic array

To free the space allocated by a dynamic array you can use one of below method:

SetLength(A, 0);
or
A:= nil;


Two dimentional Dynamic arrays:

To declare two dimention Dynamic array use below declaration:

A: array of array of Integer;

In this case you need to allocate the first dimention them allocate the second dimention
for each row:

SetLength(A, 10);  // First dimention

for i:= 0 to 9 do  
// second dimention
SetLength(
A[i], 3);

A[9, 0]:= 12;
// Put an item in array


Note:

Dynamic arrays can be used with standard data types as well as user defined such
as:


type
TRec = record
   Name: string[30];
   DOB: TDateTime;
end;

var
Recs:
array of TRec;